package com.xiaoma.listener;

import com.rabbitmq.client.Channel;
import com.xiaoma.service.OrderService;
import entity.Payorder;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author: xiaoma
 * @Date: 2021/8/2 17:49
 * @description:
 */
@Component
@RabbitListener(queues = "order.seckill.order.queue")
public class SeckillOrderListener {
    @Autowired
    private OrderService orderService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @RabbitHandler
    public void createOrder(Payorder order, Message message, Channel channel) throws IOException {
        System.out.println("***********接收到秒杀消息");
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            //创建订单
            orderService.save(order);
            //给MQ发送消息，加入延时队列
            rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order);
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            channel.basicReject(deliveryTag,true);
        }
    }
}
